﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace ServiceKit.JsonRpc
{
    [JsonObject]
    public class RpcError
    {
        public RpcError(RpcException exception, bool showServerExceptions)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }
            this.SubCode = (int)exception.ErrorCode;
            this.SubMessage = RpcError.GetErrorMessage(exception, showServerExceptions);
            this.Data = exception.Data;
        }

        /// <summary>
        /// 业务返回码
        /// </summary>
        [JsonProperty("code", Required = Required.Always)]
        public int SubCode { get; private set; }

        /// <summary>
        /// 业务返回码描述
        /// </summary>
        [JsonProperty("message", Required = Required.Always)]
        public string SubMessage { get; private set; }

        /// <summary>
        /// 数据
        /// </summary>
        [JsonProperty("data")]
        public JToken Data { get; private set; }

        private static string GetErrorMessage(Exception exception, bool showServerExceptions)
        {
            string message = exception.Message;
            if (showServerExceptions && exception.InnerException != null)
            {
                message += "\t内部异常: " + exception.InnerException.Message;
            }
            return message;
        }
    }
}
